package com.hanbang.qzzds.utils.http;

import com.hanbang.qzzds.appliction.MyApplication;
import com.hanbang.qzzds.mode.ServiceApi;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liukun on
 * 管理Retrofit 和 ServiceApi
 */
public class HttpManager {

    ///app/api4.ashx?action=
    public static final String BASE_URL = "http://api.cxgz8.com";
    public static final String BASE_API = "/app/api4.ashx";

    private static final int DEFAULT_TIMEOUT = 20;
    private static final int LONG_TIMEOUT = 200;

    public Retrofit retrofit;
    public ServiceApi serviceApi;


    //构造方法私有
    private HttpManager() {
        retrofit = getRetrofit(getRetrofitBuilder());
        //3:创建请求
        serviceApi = retrofit.create(ServiceApi.class);
        //4订阅回调数据
        //5处理返回值
    }

    private Retrofit getRetrofit(OkHttpClient.Builder builder) {
        //2：生成Retrofit实例
        return getRetrofitBuilder(builder)
                .build();
    }

    private Retrofit.Builder getRetrofitBuilder(OkHttpClient.Builder builder) {
        //2：生成Retrofit实例
        return new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(GsonHelper.getGson()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL);
    }

    public OkHttpClient.Builder getRetrofitBuilder() {
        //1：手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.retryOnConnectionFailure(true);//链接失败重新链接
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);//链接超时
        builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);//读取超时
        builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);//写入超时
        //设置缓存目录
        File cacheDirectory = new File(MyApplication.appSDCachePath, "HttpCache");
        final Cache cache = new Cache(cacheDirectory, 50 * 1024 * 1024);//
        builder.cache(cache);//设置缓存
        builder.addInterceptor(new MarvelSigningInterceptor());
        return builder;
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpManager INSTANCE = new HttpManager();
    }

    //获取单例
    public static HttpManager getInstance() {
        return SingletonHolder.INSTANCE;
    }


    public Retrofit getRetrofit() {
        return retrofit;
    }

    public OkHttpClient getOkHttpClient() {
        return (OkHttpClient) getRetrofit().callFactory();
    }


    /**
     * 单独的一个Retrofit  用于获取上传的进度
     * <p>
     * 当参数为空  就用单列的serviceApi
     *
     * @param progressCallBack
     * @return
     */
    public ServiceApi getServiceApi(final ProgressCallBack progressCallBack) {
        if (progressCallBack == null)
            return serviceApi;
        else {
            OkHttpClient.Builder builder = getRetrofitBuilder();
            builder.writeTimeout(LONG_TIMEOUT, TimeUnit.SECONDS);//写入超时

            builder.addNetworkInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {

                    //增加请求的精度回调
                    Request newRequest = chain.request().body() != null ? chain.request().newBuilder().post(new ProgressRequestBody(chain.request().body(), progressCallBack)).
                            build() : chain.request();

                    return chain.proceed(newRequest);

                }
            });
            return getRetrofit(builder).create(ServiceApi.class);
        }
    }

    /**
     * 单独的一个Retrofit  用于传大文件
     * <p>
     * 当参数为空  就用单列的serviceApi
     *
     * @return
     */
    public ServiceApi getLongServiceApi() {
        OkHttpClient.Builder builder = getRetrofitBuilder();
        builder.writeTimeout(LONG_TIMEOUT, TimeUnit.SECONDS);//写入超时
        return getRetrofit(builder).create(ServiceApi.class);
    }
}

/**
 * // newRequest.header("RANGE", "bytes=" + startPoints + "-");//断点续传要用到的，指示下载的区间
 * Response oldResponse = chain.proceed(newRequest);
 * return oldResponse.newBuilder().body(new ProgressResponseBody(oldResponse.body(), progressCallBack))//增加响应的精度回调
 * .build();
 */

